use eframe::egui::{self, Color32, Ui};
use egui_extras::{Size, StripBuilder};

pub struct TreeNode {
    label: String,
    children: Vec<TreeNode>,
    is_open: bool,
}

impl TreeNode {
    pub fn new(label: &str) -> Self {
        Self {
            label: label.to_string(),
            children: vec![],
            is_open: false,
        }
    }

    pub fn add_child(&mut self, child: TreeNode) {
        self.children.push(child);
    }

    pub fn show(&mut self, ui: &mut Ui) {
        let response = ui.collapsing(&self.label, |ui| {
            for child in &mut self.children {
                child.show(ui);
            }
        });

        // Handle the response
        self.is_open = response.header_response.clicked()
            || response.body_response.map_or(false, |r| r.clicked());
    }
}

pub struct Navigation {
    account: TreeNode,
    indicators: TreeNode,
    ea: TreeNode,
    scripts: TreeNode,
}

impl Navigation {
    pub fn new() -> Self {
        let mut account = TreeNode::new("账户");
        let mut indicators = TreeNode::new("指标");
        let mut ea: TreeNode = TreeNode::new("EA");
        let mut scripts = TreeNode::new("脚本");

        // 证券商
        let securities_firms = TreeNode::new("**证券");
        account.add_child(securities_firms);

        // 指标
        let mut trend = TreeNode::new("趋势");
        let volatility = TreeNode::new("波动");
        indicators.add_child(trend);
        indicators.add_child(volatility);

        // 趋势
        let ma = TreeNode::new("MA");
        indicators.children[0].add_child(ma);

        // 波动
        let volatility_indicators = TreeNode::new("波动指标");
        indicators.children[1].add_child(volatility_indicators);
        indicators.children[1].children[0].add_child(TreeNode::new("ATR"));

        Self {
            account: account,
            indicators: indicators,
            ea: ea,
            scripts: scripts,
        }
    }

    pub fn show(&mut self, ui: &mut Ui) {
        // let available_width = ui.available_width();
        ui.group(|ui| {
            ui.label("海贝");
            StripBuilder::new(ui)
                .size(Size::exact(50.0))
                .size(Size::remainder())
                .size(Size::relative(0.5).at_least(60.0))
                .vertical(|mut strip| {
                    strip.cell(|ui| {
                        self.account.show(ui);
                        self.indicators.show(ui);
                        self.ea.show(ui);
                        self.scripts.show(ui);
                    });
                });
        });
        // ui.group(|ui| {
        //     ui.label("海贝");
        //     self.account.show(ui);
        //     self.indicators.show(ui);
        //     self.ea.show(ui);
        //     self.scripts.show(ui);
        // });
    }
}
